/**
 * <p>Title: YihaoxueLogin.java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2015</p>
 * <p>Company: SiySoft</p>
 * @author liguanghui
 * @date 2015年5月26日
 * @version 1.0
 */
package com.siysoft.tc.base.service;

/**
 * <p>Title: MyLoginFailureSuccessHandler.java</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2015</p>
 * <p>Company: SiySoft</p>
 * @author liguanghui
 * @date 2015年5月25日
 * @version 1.0
 */

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

public class AdminLoginFailureHandler implements
		AuthenticationFailureHandler, InitializingBean {
	protected Log logger = LogFactory.getLog(getClass());
	private String defaultTargetUrl;
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	public String getDefaultTargetUrl() {
		return this.defaultTargetUrl;
	}

	public void setDefaultTargetUrl(String defaultTargetUrl) {
		this.defaultTargetUrl = defaultTargetUrl;
	}

	public void afterPropertiesSet() throws Exception {
	}

	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response,
			AuthenticationException authenticationException)
			throws IOException, ServletException {
		if ("Bad credentials".equals(authenticationException.getMessage())) {
			request.setAttribute("exception", "密码错误");
			//把用户名写进login.jsp 对应客户需求：20150703_问题整理_工时整理.xlsx #3 修改意见
			request.setAttribute("attemptedUsername", authenticationException.getAuthentication().getPrincipal().toString());
			request.getRequestDispatcher(this.defaultTargetUrl).forward(
					request, response);
		} else if ("UsernameNotFound".equals(authenticationException
				.getMessage())) {
			request.setAttribute("exception", "用户不存在");
			request.getRequestDispatcher(this.defaultTargetUrl).forward(
					request, response);
		} else {
			request.setAttribute("exception",
					authenticationException.getMessage());
			this.redirectStrategy.sendRedirect(request, response,
					this.defaultTargetUrl);
		}
	}
}
